package control;

import entity.Category;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

@WebServlet(name="NewCategory", urlPatterns={"/backend/NewCategory"})
public class NewCategory extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // TODO:
        // - Ik maak hier de EntityManagerFactory en de EntityManager op deze manier aan,
        //   Erco had hier in zijn de hartige hap project iets handigs voor bedacht
        //   We moeten dus nog afspreken hoe wij dit gaat doen
        // - POST is niet idempotent, hier moet naar gekeken worden
        boolean formSucces = false;
        
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("vh11i_jeePU");
        EntityManager em = fact.createEntityManager();
        
        Category category = new Category();
        request.setAttribute("category", category);
        
        try {
            if(request.getMethod().equals("POST")) {
                
                // TODO: foutmeldingen -> hoe?
                category.setName(request.getParameter("name"));
                
                    em.getTransaction().begin();
                    em.persist(category);
                    em.getTransaction().commit();
                    formSucces = true;

            }
        }
        catch(ConstraintViolationException ex) {
            request.setAttribute("formError", ex.getConstraintViolations());
        }
        finally {
            em.close();
            fact.close();
        }

        if (formSucces) {
            response.sendRedirect("NewCategory?success=true");
        }
        else {
            RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/newCategory.jsp");
            dispatcher.forward(request, response);
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
